/*
Add :

LIBS += -L/usr/lib \
-lvlc

to .pro file

*/

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QtDebug>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Init

    this->setWindowTitle("FreeEasyTV");

    // Setting the main window icon
    QFile icon( QCoreApplication::applicationDirPath() + "/images/tv.png");
    if( icon.exists() == true )
    {
        this->setWindowIcon(QIcon(icon.fileName()));
    }

    desinterlace_on = false;

    libvlc_exception_init (&this->_vlcexcep);
    // const char *optionDeVlc[]={"","logo:marq","--marq-marquee","HELLO" };
    const char *optionDeVlc[]={""};
    _vlcinstance = libvlc_new(sizeof(optionDeVlc) / sizeof(optionDeVlc[0]),optionDeVlc,&this->_vlcexcep);

    if(libvlc_exception_raised(&this->_vlcexcep))
    {
        //return(0);
    }

    if( _vlcinstance == NULL)
    {
        //return(0);
    }

    // Nouveau :

    // A voir : --rtp-client-port=

    player = libvlc_media_player_new(_vlcinstance,&this->_vlcexcep);
    media = libvlc_media_new(_vlcinstance, "rtsp://mafreebox.freebox.fr/fbxtv_pub/stream?namespace=1&service=201&flavour=sd", &_vlcexcep);
    libvlc_media_player_set_media(player,media,&this->_vlcexcep);
    libvlc_media_player_set_xwindow(player ,ui->frame->winId(),&this->_vlcexcep);
    libvlc_media_add_option(media,":video-filter=deinterlace",&this->_vlcexcep);
    libvlc_media_add_option(media,":deinterlace-mode=blend",&this->_vlcexcep);
    desinterlace_on = true;
    ui->checkBox_Desinterlace->setChecked(true);
    libvlc_media_player_play(player,&this->_vlcexcep);
    libvlc_audio_set_volume (_vlcinstance, 20 , &this->_vlcexcep);
    if(libvlc_exception_raised(&this->_vlcexcep))
    {
        qDebug() <<  "Exception VLC volume " << libvlc_exception_get_message(&_vlcexcep);
    }

    ui->horizontalSlider->setSliderPosition(20);

    // Request playlist

    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
    manager->get(QNetworkRequest(QUrl("http://mafreebox.freebox.fr/freeboxtv/playlist.m3u")));

    ui->centralWidget->setMouseTracking(true);

    TimerCount = 0;
    HidedRemote = false;
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(TimerTimeout()));
    timer->start(1000);
}

MainWindow::~MainWindow()
{
    PlayerStop();

    libvlc_media_player_release(player);
    libvlc_release(_vlcinstance); // last operation
    libvlc_exception_clear(&this->_vlcexcep);

    delete ui;
}

// Auto-Hide remote
void MainWindow::TimerTimeout()
{

    TimerCount++;

    if( ( TimerCount >  10 ) && ( HidedRemote == false ) )
    {
        ui->groupBoxRemote->hide();
        HidedRemote = true;
    }
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::mouseMoveEvent( QMouseEvent * ev )
{
    if( TimerCount > 3)
    {
        ui->groupBoxRemote->show();
        HidedRemote = false;
    }

    TimerCount = 0;
}

// Playlist

void MainWindow::replyFinished(QNetworkReply* Reply)
{
static QUrl old_redirection= QUrl("");

    // handle http redirection :

    QVariant possibleRedirectUrl = Reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    if( ( !possibleRedirectUrl.isNull() ) && ( possibleRedirectUrl.toUrl() != old_redirection ) ) // no loop !
    {
        qDebug() <<  "redirection to " << possibleRedirectUrl;
        old_redirection = possibleRedirectUrl.toUrl();
        manager->get(QNetworkRequest(possibleRedirectUrl.toUrl()));
        return;
    }

    // Channels :

    QList<QByteArray> list = Reply->readAll().split('\n'); // c'est de l'UTF8 !!
    QString channel_name;
    foreach(QString line, list)
    {
        if( line.startsWith("#EXTINF"))
        {
            channel_name = line.section('-',1);
        }
        else if( (line.startsWith("rtsp://")) )
        {
            QByteArray true_name = channel_name.trimmed().toLatin1();
            QListWidgetItem *item = new QListWidgetItem(QString::fromUtf8(true_name.data(),true_name.size()));
            item->setData(Qt::UserRole,QVariant(line));
            ui->listWidget->addItem(item);
        }
    }

    Reply->deleteLater();
}


// Volume :: !!!!!!!!!!!!! ne marche pas si on clique au bout du slider ( hors glisser )

void MainWindow::on_horizontalSlider_sliderMoved(int position)
{
    PlayerChangeVolume(position);
}


void MainWindow::on_horizontalSlider_valueChanged(int value)
{
    PlayerChangeVolume(value);
}

// Channel double-clicked

void MainWindow::on_listWidget_itemDoubleClicked(QListWidgetItem* item)
{
    /*
    QString test;

    QString hello = test.fromUtf8("Héllo",6);
*/

    qDebug() <<  "Channel change to : " << item->data(Qt::UserRole)  << "Name : " << item->text();
    PlayerStop();
    PlayerPlay( item->data(Qt::UserRole).toString() , item->text());
}

void MainWindow::PlayerStop()
{
    libvlc_media_player_stop(player,&this->_vlcexcep);
    while( libvlc_media_player_is_playing(player,&this->_vlcexcep) != 0 )
    {
    }
}

void MainWindow::PlayerPlay(QString url,QString text)
{

    PlayerStop();

    libvlc_media_release(media);
    media = libvlc_media_new (_vlcinstance, url.toAscii(), &_vlcexcep);
    libvlc_media_player_set_media(player,media,&this->_vlcexcep);
    this->setWindowTitle("FreeEasyTV - " + text);
    ui->checkBox_Desinterlace->setCheckState(Qt::Checked);
    libvlc_media_add_option(media,":video-filter=deinterlace", &this->_vlcexcep);
    libvlc_media_add_option(media,":deinterlace-mode=blend", &this->_vlcexcep);
    desinterlace_on = true;

    libvlc_media_player_play(player,&this->_vlcexcep);
}

void MainWindow::PlayerChangeVolume( int volume )
{
    libvlc_exception_clear(&this->_vlcexcep);
    libvlc_audio_set_volume (_vlcinstance, volume , &this->_vlcexcep);
    if(libvlc_exception_raised(&this->_vlcexcep))
    {
        qDebug() <<  "Exception VLC libvlc_audio_set_volume " << libvlc_exception_get_message(&_vlcexcep);
    }
}

void MainWindow::on_checkBox_Desinterlace_stateChanged(int )
{

    PlayerStop();

    if( ui->checkBox_Desinterlace->isChecked() == true )
    {
        qDebug() <<  "On désinterlace";
        libvlc_media_add_option(media,":video-filter=deinterlace",&this->_vlcexcep);
        libvlc_media_add_option(media,":deinterlace-mode=blend",&this->_vlcexcep);
    }
    else
    {
        qDebug() <<  "On ne désinterlace ** PAS **";
        libvlc_media_add_option(media,":video-filter=deinterlace",&this->_vlcexcep);
        libvlc_media_add_option(media,":deinterlace-mode=disabled",&this->_vlcexcep);
    }

    libvlc_media_player_set_media(player,media,&this->_vlcexcep);
    libvlc_media_player_play(player,&this->_vlcexcep);

}

void MainWindow::on_pushButton_Hide_clicked()
{
    ui->groupBoxRemote->hide();
    HidedRemote = true;
    TimerCount=2;
}

void MainWindow::on_checkBox_Mute_clicked()
{
    static int volume;

        if( ui->checkBox_Mute->isChecked() == true)
        {
            volume = libvlc_audio_get_volume(_vlcinstance,&this->_vlcexcep);
            libvlc_audio_set_volume(_vlcinstance,0,&this->_vlcexcep);
        }
        else
        {
            libvlc_audio_set_volume(_vlcinstance,volume,&this->_vlcexcep);
        }
}
